//
//  XYTableView.m
//  LabHelper
//
//  Created by 找汽配 on 2017/5/31.
//  Copyright © 2017年 XiangYun. All rights reserved.
//

#import "XYImageScrollView.h"
#import "XYImageScrollViewCell.h"
#import "XYImageScrollViewModel.h"
#import "UIColor+XY.h"

@interface XYImageScrollView () <UIScrollViewDelegate, XYImageScrollViewCellDelegate>

@property (nonatomic, weak) UIScrollView * scrollView;
@property (nonatomic, weak) UIPageControl * pageControl;

@property (nonatomic, strong) NSArray<XYImageScrollViewCell *>* cells;
@property (nonatomic, strong) NSArray<XYImageScrollViewModel *>* models;
@property (nonatomic, strong) NSTimer * timer;
@property (nonatomic, assign) NSInteger index;

@end

@implementation XYImageScrollView

- (void)awakeFromNib {
    [super awakeFromNib];
    
    UIScrollView * scrollView = [[UIScrollView alloc] init];
    scrollView.backgroundColor = [UIColor clearColor];
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.scrollEnabled = NO;
    scrollView.pagingEnabled = YES;
    scrollView.delegate = self;
    [self addSubview:scrollView];
    [self addConstraints:@[[NSLayoutConstraint constraintWithItem:scrollView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1 constant:0],
                           [NSLayoutConstraint constraintWithItem:scrollView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1 constant:0],
                           [NSLayoutConstraint constraintWithItem:scrollView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeading multiplier:1 constant:0],
                           [NSLayoutConstraint constraintWithItem:scrollView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTrailing multiplier:1 constant:0]]];
    self.scrollView = scrollView;
    
    UIView * contentView = [[UIView alloc] init];
    contentView.backgroundColor = [UIColor clearColor];
    [scrollView addSubview:contentView];
    [scrollView addConstraints:@[[NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:scrollView attribute:NSLayoutAttributeTop multiplier:1 constant:0],
                                 [NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:scrollView attribute:NSLayoutAttributeBottom multiplier:1 constant:0],
                                 [NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:scrollView attribute:NSLayoutAttributeLeading multiplier:1 constant:0],
                                 [NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:scrollView attribute:NSLayoutAttributeTrailing multiplier:1 constant:0],
                                 [NSLayoutConstraint constraintWithItem:contentView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:scrollView attribute:NSLayoutAttributeHeight multiplier:1 constant:0]]];
    
    NSInteger begin = 0;
    NSInteger end = 2;
    XYImageScrollViewCell * prevCell = nil;
    for (NSInteger i = begin; i <= end; ++i) {
        XYImageScrollViewCell * cell = [XYImageScrollViewCell cell];
        cell.delegate = self;
        [contentView addSubview:cell];
        [scrollView addConstraint:[NSLayoutConstraint constraintWithItem:cell attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:scrollView attribute:NSLayoutAttributeWidth multiplier:1 constant:0]];
        [contentView addConstraints:@[[NSLayoutConstraint constraintWithItem:cell attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:contentView attribute:NSLayoutAttributeTop multiplier:1 constant:0],
                                      [NSLayoutConstraint constraintWithItem:cell attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:contentView attribute:NSLayoutAttributeBottom multiplier:1 constant:0]]];
        if (i == begin) {
            [contentView addConstraint:[NSLayoutConstraint constraintWithItem:cell attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:contentView attribute:NSLayoutAttributeLeading multiplier:1 constant:0]];
        }
        else {
            [contentView addConstraint:[NSLayoutConstraint constraintWithItem:cell attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:prevCell attribute:NSLayoutAttributeTrailing multiplier:1 constant:0]];
        }
        if (i == end) {
            [contentView addConstraint:[NSLayoutConstraint constraintWithItem:cell attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:contentView attribute:NSLayoutAttributeTrailing multiplier:1 constant:0]];
        }
        prevCell = cell;
    }
    self.cells = contentView.subviews;
    
    UIPageControl * pageControl = [[UIPageControl alloc] init];
    pageControl.pageIndicatorTintColor = RGB(225, 225, 225);
    pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    [self addSubview:pageControl];
    [pageControl addConstraints:@[[NSLayoutConstraint constraintWithItem:pageControl attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:100],
                                  [NSLayoutConstraint constraintWithItem:pageControl attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:30]]];
    [self addConstraints:@[[NSLayoutConstraint constraintWithItem:pageControl attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1 constant:0],
                           [NSLayoutConstraint constraintWithItem:pageControl attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]]];
    self.pageControl = pageControl;
    
    NSLog(@"awake from nib");
}

- (void)dealloc {
    [self stopTimer];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    NSLog(@"layout subviews %f", self.frame.size.width);

    [self reloadDataWithOffset];
}

#pragma mark - Controller

- (void)reloadData {
    NSLog(@"reload data %d", self.index);
    [self.cells[0] setModel:[self modelAtIndex:self.index - 1]];
    [self.cells[1] setModel:[self modelAtIndex:self.index]];
    [self.cells[2] setModel:[self modelAtIndex:self.index + 1]];
    self.pageControl.currentPage = self.index;
}

- (void)reloadDataWithOffset {
    CGFloat offsetX = self.scrollView.contentOffset.x;
    CGFloat width = self.scrollView.frame.size.width;
//    NSLog(@"reload data with offset %f %f", offsetX, width);
    if (offsetX >= width * 2) {
        XYImageScrollViewModel * model = self.cells[2].model;
        self.index = [self.models indexOfObject:model];
        [self reloadData];
        offsetX = offsetX - width;
        [self.scrollView setContentOffset:CGPointMake(offsetX, 0)];
    }
    else if (offsetX < width) {
        XYImageScrollViewModel * model = self.cells[0].model;
        self.index = [self.models indexOfObject:model];
        [self reloadData];
        offsetX = offsetX + width;
        [self.scrollView setContentOffset:CGPointMake(offsetX, 0)];
    }
}

- (XYImageScrollViewModel *)modelAtIndex:(NSUInteger)index {
    if (self.models.count > 0) {
        index = (index + self.models.count) % self.models.count;
        return self.models[index];
    }
    else {
        return nil;
    }
}

#pragma mark - Start & Stop

- (void)startTimer {
    [self stopTimer];
    
    if (self.models.count > 0) {
        self.timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(scrollImage) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];        
    }
}

- (void)stopTimer {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)scrollImage {
    [self reloadDataWithOffset];
    CGFloat width = self.scrollView.frame.size.width;
    // 自动滚动
    // 该方法仅会调用scrollViewDidScroll，不会调用其他方法
    [self.scrollView setContentOffset:CGPointMake(width * 2, 0) animated:YES];
}

#pragma mark - Setter

- (void)setDefaultImage:(UIImage *)defaultImage {
    _defaultImage = defaultImage;
    
    [self.cells enumerateObjectsUsingBlock:^(XYImageScrollViewCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.defaultImage = defaultImage;
    }];
}

- (void)setImages:(NSArray<UIImage *>*)images {
    NSLog(@"set images");

    NSMutableArray * mArray = [NSMutableArray arrayWithCapacity:images.count];
    [images enumerateObjectsUsingBlock:^(UIImage * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        XYImageScrollViewModel * model = [XYImageScrollViewModel model];
        model.action = self.modelAction;
        model.image = obj;
        [mArray addObject:model];
    }];
    self.models = [mArray copy];
    self.scrollView.scrollEnabled = self.models.count > 0;
    self.pageControl.numberOfPages = self.models.count;
    [self reloadData];
    [self reloadDataWithOffset];
    [self startTimer];
}

- (void)setImageURLs:(NSArray<NSString *>*)imageURLs {
    NSLog(@"set image URLs");

    NSMutableArray * mArray = [NSMutableArray arrayWithCapacity:imageURLs.count];
    [imageURLs enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        XYImageScrollViewModel * model = [XYImageScrollViewModel model];
        model.action = self.modelAction;
        model.imageURL = obj;
        [mArray addObject:model];
    }];
    self.models = [mArray copy];
    self.scrollView.scrollEnabled = self.models.count > 0;
    self.pageControl.numberOfPages = self.models.count;
    [self reloadData];
    [self reloadDataWithOffset];
    [self startTimer];
}

#pragma mark - UIScrollViewDelegate

// 滑动处理
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self reloadDataWithOffset];
}

// 开始拖动
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self stopTimer];
}

// 结束拖动
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self startTimer];
}

//- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
//
//}

// 结束减速滚动
// 自动滚动不会调用该方法，只有手动拖动才会调用该方法
//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
//    NSLog(@"scroll view did end decelerating");
//    [self reloadDataWithOffset];
//}

#pragma mark - XYImageScrollViewCellDelegate

- (void)imageScrollViewCellDidSelectWithModel:(XYImageScrollViewModel *)model {
    if (self.delegate && [self.delegate respondsToSelector:@selector(imageScrollViewDidSelectImageAtIndex:)]) {
        [self.delegate imageScrollViewDidSelectImageAtIndex:[self.models indexOfObject:model]];
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
